package controllers

import (
	"dog/models"
	beego "github.com/beego/beego/v2/server/web"
	"math"
)

type Dogcontroller struct {
	beego.Controller
}

func (c *Dogcontroller) Upload() {
	file, head, err := c.GetFile("img")
	if err != nil {
		return
	}
	defer file.Close()
	if head.Size > 1024*1024*2 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "图片大小不能超过2M大小",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	path := "static/img/" + head.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "上传成功",
			Data: "http://127.0.0.1:8080" + path,
		}
		c.ServeJSON()
	}

}

func (c *Dogcontroller) Add() {
	name := c.GetString("name")
	age, _ := c.GetInt("age")
	img := c.GetString("img")
	price, _ := c.GetFloat("price")

	dog := models.Dog{
		Name:  name,
		Age:   age,
		Img:   img,
		Price: price,
	}
	err := models.DB.Create(&dog).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *Dogcontroller) Limit() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)

	offset := (page - 1) * size
	var count int64
	models.DB.Count(&count)
	sum := int(math.Ceil(float64(count) / float64(size)))
	up := page - 1
	if up < 1 {
		up = 1
	}

	down := page + 1
	if down > sum {
		down = sum
	}

	var dog models.Dog

	err := models.DB.Limit(size).Offset(offset).Find(&dog).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		pageData := make(map[string]interface{})
		pageData["count"] = count
		pageData["sum"] = sum
		pageData["up"] = up
		pageData["down"] = down
		pageData["dog"] = dog
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

func (c *Dogcontroller) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Dog{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
